import { NextRequest, NextResponse } from 'next/server';
import { verifyCredentials, createAuthToken } from '@/lib/auth';
import { cookies } from 'next/headers';

export async function POST(request: NextRequest) {
  try {
    const { username, password } = await request.json();
    
    if (!username || !password) {
      return NextResponse.json(
        { success: false, message: '请输入用户名和密码' },
        { status: 400 }
      );
    }
    
    // 验证用户凭据
    if (!verifyCredentials(username, password)) {
      console.log('登录失败: 用户名或密码错误', { username });
      return NextResponse.json(
        { success: false, message: '用户名或密码错误' },
        { status: 401 }
      );
    }
    
    // 创建认证token
    const token = createAuthToken();
    console.log('登录成功，设置cookie', { username, token });
    
    // 设置认证cookie
    const response = NextResponse.json({
      success: true,
      message: '登录成功',
      user: { name: '管理员', role: 'admin' }
    });
    
    // 使用兼容性最好的cookie设置
    const cookieOptions = {
      httpOnly: false, // 客户端需要读取
      secure: false, // HTTP环境必须为false
      sameSite: 'lax' as const, // 更好的兼容性
      maxAge: 60 * 60 * 24 * 7, // 7天
      path: '/', // 确保路径正确
    };
    
    response.cookies.set('admin-token', token, cookieOptions);
    
    console.log('设置cookie完成', { token, cookieOptions });
    
    return response;
    
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '服务器错误' },
      { status: 500 }
    );
  }
}